#include "gestionFile.h"

void InitialiseGFile(gFile * gFil, const int maxSock)
{
  pthread_mutex_init(&(gFil->mut), NULL);
  pthread_cond_init(&(gFil->non_vide), NULL);
  pthread_cond_init(&(gFil->non_plein), NULL);
  gFil->maxSock=maxSock;
  gFil->nbSock=0;
  /* Creation d'un file descriptor pour communiquer avec les threads */
  if(socketpair(AF_UNIX, SOCK_STREAM, 0, gFil->sockPair) != 0) {
    perror("opening stream socket pair");
    exit(1);
  }
  initializes_List(&(gFil->file), initialisationCopEltInt, testamentEltInt, afficherEltInt, comparaisonEltInt);
}

void TestamentGFile(gFile * gFil)
{
  testament_List(&(gFil->file));
  pthread_mutex_destroy(&(gFil->mut));
  pthread_cond_destroy(&(gFil->non_vide));
  pthread_cond_destroy(&(gFil->non_plein));
}

int InsererFile(int sock, gFile * gFile){
  pthread_mutex_lock(&(gFile->mut));
  while(gFile->nbSock == gFile->maxSock)
    {
      pthread_cond_wait(&gFile->non_plein, &gFile->mut);
      if(STOP == 1)
	{
	  pthread_mutex_unlock(&(gFile->mut));
	  return 1;
	}
    }
  if(insertLast_List(&sock, &gFile->file) == LIST_ERR){
    pthread_mutex_unlock(&(gFile->mut));
    return 1;
  }else{
    gFile->nbSock++;
    pthread_cond_signal(&gFile->non_vide);
  }
  pthread_mutex_unlock(&(gFile->mut));
  return 0;
}

int DepilerFile(gFile * gFile){
  int sock;
  int * psock = NULL;
  pthread_mutex_lock(&(gFile->mut));
  while(gFile->nbSock == 0)
    {
      pthread_cond_wait(&gFile->non_vide, &gFile->mut);
      if(STOP == 1)
	{
	  pthread_mutex_unlock(&(gFile->mut));
	  return -1;
	}
    }
  psock = (int*)getDataFirst_List(&gFile->file);
  sock = *psock;
  if(deleteFirst_List(&gFile->file) == LIST_ERR){
    fprintf(stdout, "Erreur de suppression dans la file\n");
    pthread_mutex_unlock(&(gFile->mut));
    return -1;
  }else{
    gFile->nbSock--;
  }
  pthread_mutex_unlock(&(gFile->mut));
  return sock;
}

